﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using DataAccessLayer;
using PurchaseOrderExtra;
using MyException;

namespace PresentationLayer
{
    public partial class ReceiveDelivery : System.Web.UI.Page
    {
        ReceiveDeliveryControl control;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                #region Check if user exists and has permission to view this page
                if (Session["UserLoggedIn"] != null)
                {
                    List<string> list = Session["UserLoggedIn"] as List<string>;
                    if (list[0].Equals("validuser"))
                    {
                        int roleId = Convert.ToInt32(list[6]);
                        if (roleId != 5)
                        {
                            Response.Redirect("/AccessDenied.aspx");
                        }
                    }
                    else
                    {
                        Response.Redirect("/Login.aspx");
                    }
                }
                else
                {
                    Response.Redirect("/Login.aspx");
                }
                #endregion

                control = new ReceiveDeliveryControl();

                if (!IsPostBack)
                {
                    ResetFieldsExceptPONo();

                    HideFields();
                }

                // Block the button to prevent multiple clicks by the user
                btnConfirm.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(btnConfirm).ToString() + ";");
            }
            catch (Exception ex)
            {
                btnConfirm.Enabled = true;
            }
        }

        protected void ibtnCalendar_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                CalendarDeliveryDate.Visible = true;
            }
            catch (Exception ex)
            {
            }
        }

        protected void CalendarDeliveryDate_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                txtDeliveryDate.Text = CalendarDeliveryDate.SelectedDate.ToShortDateString();
                CalendarDeliveryDate.SelectedDates.Clear();
                CalendarDeliveryDate.Visible = false;
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            lblMessage.Text = "";
            ResetFieldsExceptPONo();
            int poId = 0;
            List<DeliveryDisplay> list = new List<DeliveryDisplay>();
            try
            {
                poId = Convert.ToInt32(txtPONo.Text.Trim());
                list = control.GetDeliveryDisplayByPOId(poId);

                if (list.Count > 0)
                {
                    gvDeliveryOrder.DataSource = list;
                    gvDeliveryOrder.DataBind();

                    PurchaseOrder purchaseOrder = control.GetPurchaseOrderByPOId(poId);
                    lblTitlePO.Text = "Purchase Order No " + poId.ToString();

                    string status = purchaseOrder.Status;
                    if (status == "Approved")
                    {
                        txtDeliveryDate.Text = "";
                        txtDeliveryOrderNo.Text = "";
                        UnhideFieldsAndEnableField();
                    }
                    if (status == "Delivered")
                    {
                        UnhideFieldsAndEnableField();
                        HideButtonsAndDisableField();
                        txtDeliveryOrderNo.Text = purchaseOrder.DeliveryOrderNo;
                        txtDeliveryDate.Text = purchaseOrder.DeliveryDate.Value.ToShortDateString();
                        lblMessage.Text = "Purchase Order No " + poId + " was received on " + txtDeliveryDate.Text;
                    }
                    else if (status == "Pending")
                    {
                        HideFields();
                        lblMessage.Text = "Purchase Order No " + poId + " is still pending for approval";
                    }
                    else if (status == "Rejected")
                    {
                        HideFields();
                        lblMessage.Text = "Purchase Order No " + poId + " was rejected";
                    }
                }
                else
                {
                    HideFields();
                    if (poId > 0)
                    {
                        lblMessage.Text = "Purchase Order No " + poId + " does not exist";
                    }
                }
            }
            catch (FormatException ex)
            {
                HideFields();
                // Continue with form validation
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            lblMessage.Text = "";

            if (gvDeliveryOrder.Rows.Count <= 0)
            {
                lblError.Text = "Please enter a valid Purchase Order No";
                lblError1.Text = "*";
            }
            else
            {
                Label lblPOId = null;
                int poId = 0;

                string deliveryOrderNo = "";
                DateTime deliveryDate;
                try
                {
                    lblPOId = (Label)gvDeliveryOrder.Rows[0].FindControl("lblPOId");
                    poId = Convert.ToInt32(lblPOId.Text.Trim());
                    deliveryOrderNo = txtDeliveryOrderNo.Text.Trim();
                    if (deliveryOrderNo == "")
                    {
                        throw new NoDeliveryOrderException();
                    }
                    deliveryDate = Convert.ToDateTime(txtDeliveryDate.Text);
                    if (deliveryDate.Date > DateTime.Today.Date)
                    {
                        throw new DeliveryDateAfterTodayException();
                    }
                    // Update database
                    control.UpdateDeliveryOrderInfo(poId, deliveryOrderNo, deliveryDate);

                    // Display success message and clear fields
                    ResetFieldsExceptPONo();
                    HideFields();
                    lblMessage.Text = "The delivery details for Purchase Order No " + poId + " has been saved";
                    txtPONo.Text = "";
                }
                catch (NoDeliveryOrderException ex)
                {
                    // Continue with form validation
                    btnConfirm.Enabled = true;
                }
                catch (FormatException ex)
                {
                    // Continue with form validation
                    btnConfirm.Enabled = true;
                }
                catch (DeliveryDateAfterTodayException ex)
                {
                    // Continue with form validation
                    btnConfirm.Enabled = true;
                    lblDateError.Text = "* Delivery date cannot be after today date";
                    lblDateError1.Text = "*";
                }
                catch (DeliveryDateBeforeRequestedDateException ex)
                {
                    // Continue with form validation
                    btnConfirm.Enabled = true;
                    lblDateError.Text = "* Delivery date cannot be before requested date";
                    lblDateError1.Text = "*";
                }
                catch (PendingPurchaseOrderException ex)
                {
                    btnConfirm.Enabled = true;
                    lblMessage.Text = "Purchase Order No " + poId + " is still pending for approval";
                }
                catch (RejectedPurchaseOrderException ex)
                {
                    btnConfirm.Enabled = true;
                    lblMessage.Text = "Purchase Order No " + poId + " was rejected";
                }
                catch (DeliveredPurchaseOrderException ex)
                {
                    btnConfirm.Enabled = true;
                    lblMessage.Text = "The delivery details for Purchase Order No " + poId + " had been saved previously";
                }
                catch (Exception ex)
                {
                    btnConfirm.Enabled = true;
                }
            }
        }

        private void ClearGridView()
        {
            List<DeliveryDisplay> list = new List<DeliveryDisplay>();
            gvDeliveryOrder.DataSource = list;
            gvDeliveryOrder.DataBind();
        }

        private void ResetFields()
        {
            txtPONo.Text = "";
            lblTitlePO.Text = "";
            ClearGridView();
            txtDeliveryOrderNo.Text = "";
            lblMessage.Text = "";
            lblError.Text = "";
            lblError1.Text = "";
            lblDateError.Text = "";
            lblDateError1.Text = "";
        }

        private void ResetFieldsExceptPONo()
        {
            lblTitlePO.Text = "";
            ClearGridView();
            txtDeliveryOrderNo.Text = "";
            lblMessage.Text = "";
            lblError.Text = "";
            lblError1.Text = "";
            lblDateError.Text = "";
            lblDateError1.Text = "";
        }

        private void HideFields()
        {
            lblDeliveryOrderNo.Visible = false;
            txtDeliveryOrderNo.Visible = false;
            lblDeliveryDate.Visible = false;
            txtDeliveryDate.Visible = false;
            ibtnCalendar.Visible = false;
            btnConfirm.Visible = false;
        }

        private void UnhideFieldsAndEnableField()
        {
            txtDeliveryOrderNo.Enabled = true;

            lblDeliveryOrderNo.Visible = true;
            txtDeliveryOrderNo.Visible = true;
            lblDeliveryDate.Visible = true;
            txtDeliveryDate.Visible = true;
            ibtnCalendar.Visible = true;
            btnConfirm.Visible = true;
        }

        private void HideButtonsAndDisableField()
        {
            txtDeliveryOrderNo.Enabled = false;

            ibtnCalendar.Visible = false;
            btnConfirm.Visible = false;
            CalendarDeliveryDate.Visible = false;
        }

    }
}